<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row type="flex" justify="space-start">
          <a-col :md="24" :sm="12">
            <a-row :gutter="12">
              <a-col :md="5" :sm="6" >
                <a-input
                    v-model="queryParam.enterpriseName"
                    placeholder="企业名称"
                  >
                  </a-input>
              </a-col>
              <a-col
            :md="5"
            :sm="6"
          >
          <a-select
                v-model="queryParam.batchStatus"
                placeholder="批次状态"
                allowClear
              >
                <a-select-option
                  v-for="(value, name) in batchStatus"
                  :key="name"
                  :value="name"
                >
                  {{ value }}
                </a-select-option>
              </a-select>
          </a-col>
          <a-col
            :md="5"
            :sm="6"
          >
          <a-select
                v-model="queryParam.invoiceStatus"
                placeholder="发票状态"
                allowClear
              >
                <a-select-option
                  v-for="(value, name) in invoiceStatus"
                  :key="name"
                  :value="name"
                >
                  {{ value }}
                </a-select-option>
              </a-select>
          </a-col>
          <a-col
            :md="5"
            :sm="6"
          >
          <a-select
                v-model="queryParam.bankVoucherStatus"
                placeholder="是否回单"
                allowClear
              >
                <a-select-option
                  v-for="(value, name) in bankVoucherStatus"
                  :key="name"
                  :value="name"
                >
                  {{ value }}
                </a-select-option>
              </a-select>
          </a-col>
          
              
            </a-row>
            
          </a-col>
          <a-col :md="24" :sm="12">
          <a-row :gutter="12" type="flex" style="margin-top: 10px;">
            <a-col :md="5" :sm="6" >
              <a-range-picker :placeholder="['支付时间起', '支付时间止']" style="width: 100%;"
                                  v-model="date" @change="onChange" />
              </a-col>

              <a-col :md="5" :sm="6" >
                <a-range-picker :placeholder="['创建时间起', '创建时间止']" style="width: 100%;"
                                  v-model="createDate" @change="onCreateTimeChange" />
              </a-col>

              <a-col :md="4" :sm="8">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="handleSearch">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </span>
              </a-col>
          </a-row>
        </a-col>
        </a-row>
        
        
      </a-form>
    </div>
    <div class="table-operator">
      <a-button
        :disabled="!selectedRowKeys.length"
        type="primary"
        icon="download"
        @click="handleExportExcel"
      >导出</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record, index)=> index"
      :columns="columns"
      :data="loadData"
      showPagination="auto"
      :scroll="{ x: true}"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      :title="footerShow"
      :footer="footerShow"
    >
      <span
        slot="action"
        slot-scope="text, record"
      >
        <template>
<!--          <a-->
<!--            v-if="record.settleStatus === 2"-->
<!--            @click="handleOpenUpdateStatusModel(record)"-->
<!--            disabled-->
<!--          >支付</a>-->
<!--          <a-->
<!--            v-else-->
<!--            @click="handleOpenUpdateStatusModel(record)"-->
<!--          >支付</a>-->
<!--          <a-divider type="vertical" />-->
<!--          <a-->
<!--            v-if="record.invoiceNum"-->
<!--            @click="handleOpenAddBillModal(record)">发票</a>-->
<!--          <a-->
<!--            v-else-->
<!--            @click="handleOpenAddBillModal(record)">添加发票</a>-->
<!--          <a-divider type="vertical" />-->
          <a v-if="record.invoiceNum" @click="handleOpenAddBillModal(record)">查看发票</a>
          <span v-else>暂无发票</span>
          <a-divider type="vertical" />

          <span v-if="!record.bankVoucher"> 暂无回单</span>
          <a v-else @click="handleOpenAddBackModal(record)">查看回单</a>
          <a-divider type="vertical" />

          <a @click="handleOpenPaymentDetailModel(record)">详情</a>
        </template>
      </span>
    </s-table>

    <batch-detail-modal
      ref="batchDetailModal"
      @orderAction="handleOpenOrderDetailModal"
    />
    <add-bill-modal
      @onSuccess="onAddBillSuccess"
      ref="addBillModal"
    />
    <order-detail-modal ref="orderDetailModal" />
    <update-status-modal
      ref="updateStatusModal"
      @updateStatus="handleUpdateStatus"
    />
    <add-back-modal @onSuccess="onAddBillSuccess" ref="addBackModal" />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BatchDetailModal from './components/BatchDetailModal'
import AddBillModal from './components/AddBillModal'
import AddBackModal from './components/AddBackModal'
import OrderDetailModal from './components/OrderDetailModal'
import UpdateStatusModal from './components/UpdateStatusModal'
import { getPaymentList, updateBatchOrOrderStatus } from '@/api/manage'
import { BATCH_LIST_COLUMNS, BATCH_STATUS, BANK_STATUS, INVOICE_STATUS } from './constants/payment'
import { exportJsonToExcel, getHeaderAndDataFromTable } from '@/utils/exportExcel'
import { formatMoney } from '@/filter/index.js'
import NP from 'number-precision'

export default {
  name: 'BatchListPage',
  components: {
    STable,
    Ellipsis,
    BatchDetailModal,
    AddBillModal,
    OrderDetailModal,
    UpdateStatusModal,
    AddBackModal
  },
  computed: {
    
    totalFeeMoney () {
      let total = 0
      this.selectedRows.forEach(item => {
        total = NP.plus(total,item.totalFee)
      })
      return formatMoney(total)
    },
    afterFeeMoney(){
      let total = 0
      this.selectedRows.forEach(item => {
        total = NP.plus(total,item.afterFee)
      })
      return formatMoney(total)
    },
    manageFeeMoney(){
      let total = 0
      this.selectedRows.forEach(item => {
        total = NP.plus(total,item.manageFee)
      })
      return formatMoney(total)
    },
  },
  data() {
    return {
      queryParam: {},
      createDate: [],
      date: [],
      columns: BATCH_LIST_COLUMNS,
      batchStatus: BATCH_STATUS,
      bankVoucherStatus: BANK_STATUS,
      invoiceStatus: INVOICE_STATUS,
      loadData: parameter => {
        if (!this.queryParam.bankVoucherStatus){
          delete this.queryParam.bankVoucherStatus
        }
        if (!this.queryParam.batchStatus) {
          delete this.queryParam.batchStatus
        }
        if (!this.queryParam.invoiceStatus) {
          delete this.queryParam.invoiceStatus
        }
        return getPaymentList(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.resData
          })
      },
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  methods: {
    handleSearch(){
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    footerShow(){
      return(
        <temlpate>
        <div class="summary">
        <span>总金额：￥{this.totalFeeMoney}</span>
      <span>服务费：￥{this.manageFeeMoney}</span>
      <span>众包费：￥{this.afterFeeMoney}</span>
      </div>
      </temlpate>
    )
    },
    onAddBillSuccess(){
      this.$message.success('处理成功')
      this.$refs.table.refresh()
    },
    reset() {
      this.queryParam = {}
      this.date = []
      this.createDate = []
    },
    onChange(date, dateString) {
      console.log(dateString)
      this.queryParam.startTime = dateString[0]? dateString[0] + ' 00:00:00':''
      this.queryParam.endTime = dateString[1]? dateString[1] + ' 23:59:59':''
    },
    onCreateTimeChange(date, dateString) {
      console.log(dateString)
      this.queryParam.createStartTime = dateString[0]? dateString[0] + ' 00:00:00':''
      this.queryParam.createEndTime = dateString[1]? dateString[1] + ' 23:59:59':''
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleOpenUpdateStatusModel(record) {
      console.log(record)
      this.$refs.updateStatusModal.show({ batchId: record.batchId })
    },
    handleOpenAddBillModal(record) {
      console.log(record)
      this.$refs.addBillModal.show(record)
    },
    handleOpenAddBackModal(record) {
      console.log(record)
      this.$refs.addBackModal.show(record)
    },
    handleOpenPaymentDetailModel(record) {
      this.$refs.batchDetailModal.show(record.batchId)
    },
    handleOpenOrderDetailModal(projectId, individualUserId, projectMemberId) {
      this.$refs.orderDetailModal.show(projectId, individualUserId, projectMemberId)
    },
    handleUpdateStatus(updateStatusParams, callback) {
      updateBatchOrOrderStatus(updateStatusParams)
        .then(res => {
          this.$refs.table.refresh()
          callback()
        }).catch(err => {
        callback(err)
      })
    },
    handleExportExcel() {
      const { header, data } = getHeaderAndDataFromTable(
        BATCH_LIST_COLUMNS,
        this.selectedRows
      )

      exportJsonToExcel({
        header,
        data,
        filename: `结算支付列表_${+new Date()}`
      })
    },
    change(value) {
      console.log(value)
      if (value === undefined) {
        this.queryParam = {}
      }
    },
  }
}
</script>
